import axios from 'axios'

import store from '@/store'
import { getToken } from '@/utils/auth'

const { devMockURL } = require('@/api')

export const uploadHeaders = {
	Authorization: getToken()
}

const service = axios.create({
	baseURL: devMockURL,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 1000, // request timeout
	headers: {
		'Content-Type': 'application/json;charset=UTF-8'
	}
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		if (store.getters.token) {
			// let each request carry token
			// ['X-Token'] is a custom headers key
			// please modify it according to the actual situation
			config.headers['X-Token'] = getToken()
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data

		if (response.config.responseType == 'blob') {
			return Promise.resolve(res)
		} else {
			if (res === '' || res === void 0 || res === null) {
				console.log(response)
				$error(`Error：${response.config.url} response.data does not exist ！`)
				return res
			} else if (res.code == 1 || res.code === 20000) {
				return Promise.resolve(res.data === null ? response : res)
			} else if (
				res.code == 5001 ||
				res.code === 50008 ||
				res.code === 50012 ||
				res.code === 50014
			) {
				store.dispatch('user/resetToken').then(() => {
					location.reload()
				})
			} else {
				$error(res.msg || res.message || 'unknown error --- ')
				return Promise.reject(res)
			}
		}
	},
	error => {
		if (error && error.response) {
			switch (error.response.status) {
				case 400:
					error.message = '请求错误(400)'
					break
				case 401:
					error.message = '未授权，请重新登录(401)'
					break
				case 403:
					if (error.response.data && error.response.data.code === 5001) {
						error.message = error.response.data.msg
					} else {
						error.message = '拒绝访问(403)'
					}
					break
				case 404:
					error.message = '请求出错(404)'
					break
				case 408:
					error.message = '请求超时(408)'
					break
				case 500:
					error.message = '服务器错误(500)'
					break
				case 501:
					error.message = '服务未实现(501)'
					break
				case 502:
					error.message = '网络错误(502)'
					break
				case 503:
					error.message = '服务不可用(503)'
					break
				case 504:
					error.message = '网络超时(504)'
					break
				case 505:
					error.message = 'HTTP版本不受支持(505)'
					break
				default:
					error.message = `连接出错(${error.response.status})!`
			}
		}

		if (error.message && error.message.indexOf('timeout') !== -1) {
			error.message = '请求超时'
		}

		if (error.response.data && error.response.data.code === 5001) {
			store.dispatch('user/resetToken').then(() => {
				location.reload()
			})
		}

		error.message && $error(error.message)

		return Promise.reject({ ...error.response })
	}
)

export function post(url, params) {
	// post请求
	return new Promise((resolve, reject) => {
		service
			.post(url, params)
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

export function get(url, params) {
	// get请求
	return new Promise((resolve, reject) => {
		service
			.get(url, { params })
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

export function exportExcel(url, params) {
	// 导出
	return new Promise((resolve, reject) => {
		service({
			method: 'get',
			url: url,
			params: params,
			responseType: 'blob'
		})
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

export function upload(url, files, config) {
	// 上传
	return new Promise((resolve, reject) => {
		service
			.post(url, files, {
				'Content-Type': 'multipart/form-data',
				...config
			})
			.then(res => {
				resolve(res.data)
			})
			.catch(err => reject(err))
	})
}

export default service
